//
//  GPSNaviViewController.m
//  AMapNaviKit
//
//  Created by liubo on 7/29/16.
//  Copyright © 2016 AutoNavi. All rights reserved.
//

#import "GPSNaviViewController.h"
#import "SpeechSynthesizer.h"
#import "GPSInfoBaseView.h"
@interface GPSNaviViewController ()<AMapNaviWalkManagerDelegate, AMapNaviWalkViewDelegate, AMapNaviWalkDataRepresentable>

@property (nonatomic, strong) AMapNaviPoint *startPoint;
@property (nonatomic, strong) AMapNaviPoint *endPoint;
@property (nonatomic, strong) GPSInfoBaseView * GPSInfoBaseView;
@property (nonatomic, strong) RACCommand *contractCommend;
@property (nonatomic, strong) RACCommand *exChangeCommend;
@property (nonatomic, strong) NSArray * sbContract;
@property (nonatomic, strong) NSMutableArray * emergency_voices;
@property (nonatomic, strong) NSDictionary * helpInfo;
@property (nonatomic, weak) IBOutlet UIView *GPSInfoView;
@property (nonatomic, weak) IBOutlet UILabel *turnRemainInfoLabel;
@property (nonatomic, weak) IBOutlet UILabel *roadInfoLabel;
@property (nonatomic, weak) IBOutlet UILabel *routeRemainInfoLabel;
@property (nonatomic, weak) IBOutlet UILabel *roadBeforeLabel;
@property (weak, nonatomic) IBOutlet UIButton *startGPS;
@property (weak, nonatomic) IBOutlet UIView *buttonClickView_before;
@property (weak, nonatomic) IBOutlet UIView *buttonClickView_after;
@property (weak, nonatomic) IBOutlet UIView *stopGPSView;
@property (weak, nonatomic) IBOutlet UIButton *backToNow;
@property (weak, nonatomic) IBOutlet UIButton *refreshButton;
@end

@implementation GPSNaviViewController

#pragma mark - Life Cycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initDriveView];
    [self initDriveManager];
    [self initSubView];
    @weakify(self);
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    self.contractCommend = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        @strongify(self);
        [self callPhonesActionSheet: input];
        return [RACSignal empty];
    }];
    self.exChangeCommend = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id index) {
        @strongify(self);
        if([[index class] isSubclassOfClass:[NSNumber class]]){
//            NSLog(@"self.emergency_voices====%@",self.emergency_voices);
            NSMutableDictionary * voiceDic = [NSMutableDictionary dictionaryWithDictionary:self.emergency_voices[[index integerValue]]];
            [voiceDic setObject:@"1" forKey:@"listened"];
            [self.emergency_voices replaceObjectAtIndex:[index integerValue] withObject:voiceDic];
        }
        if([[index class] isSubclassOfClass:[NSArray class]]){
//            NSLog(@"self.emergency_voices====%@",self.emergency_voices);
            NSMutableDictionary * voiceDic = [NSMutableDictionary dictionaryWithDictionary:self.emergency_voices[[index[0] integerValue]]];
            [voiceDic setObject:index[1] forKey:@"wav_url"];
            [self.emergency_voices replaceObjectAtIndex:[index[0] integerValue] withObject:voiceDic];
        }
        return [RACSignal empty];
    }];
    [self.backAction setTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
}
-(void) initSubView{
    self.stopGPSView.layer.shadowColor = [UIColor grayColor].CGColor;
    self.stopGPSView.layer.shadowOffset=CGSizeMake(10, 10);
    self.stopGPSView.layer.shadowOpacity=0.5;
    self.stopGPSView.layer.shadowRadius=5;
    [self.startGPS setEnabled:NO];
    [self.startGPS addTarget:self action:@selector(startToGPS) forControlEvents:UIControlEventTouchUpInside];
    [self.backToNow setHidden:YES];
    [self.backToNow addTarget:self action:@selector(backToCarPositionLocked) forControlEvents:UIControlEventTouchUpInside];
    [self.refreshButton setHidden:YES];
    [self.refreshButton addTarget:self action:@selector(refreshGPSInfo) forControlEvents:UIControlEventTouchUpInside];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillAppear:YES];
    [self.navigationController.navigationBar setHidden:NO];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self getSbContractinfo];
    [self getThisHelpDetail];
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:YES];
    [self clearThisViewController];
}
#pragma mark - Initalization
-(GPSInfoBaseView *)GPSInfoBaseView{
    if(!_GPSInfoBaseView){
        NSArray* nibView     = [[NSBundle mainBundle] loadNibNamed:@"GPSInfoBaseView" owner:nil options:nil];
        _GPSInfoBaseView       = [nibView objectAtIndex:0];
        _GPSInfoBaseView.frame = self.view.frame;
        _GPSInfoBaseView.contractCommend = self.contractCommend;
        _GPSInfoBaseView.exChangeCommend = self.exChangeCommend;
    }
    return _GPSInfoBaseView;
}
- (void)initPropertiesLat:(NSString *)lat AndLng:(NSString *)lng
{
    //为了方便展示,选择了固定的起终点
//    self.startPoint = [AMapNaviPoint locationWithLatitude:[lat floatValue] longitude:121.454756];
    self.endPoint   = [AMapNaviPoint locationWithLatitude:[lat floatValue] longitude:[lng floatValue]];
}

- (void)initDriveManager
{
    if (self.driveManager == nil)
    {
        self.driveManager = [[AMapNaviWalkManager alloc] init];
        [self.driveManager setDelegate:self];
        
        [self.driveManager setAllowsBackgroundLocationUpdates:YES];
        [self.driveManager setPausesLocationUpdatesAutomatically:NO];
        [self.driveManager addDataRepresentative:self];
        //将driveView添加为导航数据的Representative，使其可以接收到导航诱导数据
        [self.driveManager addDataRepresentative:self.driveView];
    }
}

- (void)initDriveView
{
    if (self.driveView == nil)
    {
        self.driveView = [[AMapNaviWalkView alloc] init];
        [self.driveView setDelegate:self];
        [self.driveView setShowUIElements:NO];
        [self.driveView setStartPointImage:nil];
        [self.view insertSubview:self.driveView belowSubview:self.GPSInfoView];
        @weakify(self)
        [self.driveView mas_makeConstraints:^(MASConstraintMaker *make) {
            @strongify(self)
            make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
        }];
    }
}
-(NSDictionary *)helpInfo{
    if(!_helpInfo){
        _helpInfo =[NSDictionary dictionary];
    }
    return _helpInfo;
}
-(NSMutableArray *)emergency_voices{
    if(!_emergency_voices){
        _emergency_voices = [NSMutableArray array];
    }
    return _emergency_voices;
}
#pragma mark - Route Plan

- (void)calculateRoute
{
    [self.driveManager calculateWalkRouteWithEndPoints:@[self.endPoint]];
}
-(void)startToGPS{ //开始导航
    [self.driveManager startGPSNavi];
    [self.driveView setShowMode:AMapNaviWalkViewShowModeCarPositionLocked];
    [self.startGPS setHidden:YES];
    [self.backAction setHidden:YES];
    [self.buttonClickView_before setHidden:YES];
    [self.GPSInfoView setHidden:NO];
    [self.stopGPSView setHidden:NO];
    [self.refreshButton setHidden:NO];
    [self.buttonClickView_after setHidden:NO];
}
-(void)backToCarPositionLocked{
    [self.driveView setShowMode:AMapNaviWalkViewShowModeCarPositionLocked];
}
-(void)refreshGPSInfo{//刷新定位数据 重新规划路线
    [self stopWalkManager:nil];
    [self getThisHelpDetail];
}
- (IBAction)stopWalkManager:(id)sender {
    //停止导航
    [self.driveManager stopNavi];
    [self calculateRoute]; // 重新规划路线
//    [self.driveManager removeDataRepresentative:self.driveView];
    //停止语音
    [[SpeechSynthesizer sharedSpeechSynthesizer] stopSpeak];
    [self.startGPS setHidden:NO];
    [self.backAction setHidden:NO];
    [self.GPSInfoView setHidden:YES];
    [self.stopGPSView setHidden:YES];
    [self.refreshButton setHidden:YES];
    [self.buttonClickView_after setHidden:YES];
    [self.buttonClickView_before setHidden:NO];
}
- (IBAction)playRecoder:(id)sender {
    UIButton * button = sender ;
    NSLog(@"x =========== %f",button.frame.origin.x);
    NSLog(@"width ======= %f",button.width);
    [self.view addSubview:self.GPSInfoBaseView];
    [UIView animateWithDuration:0.6 animations:^(void){
        self.GPSInfoBaseView.alpha =1.0f;
    }];
    if(button.frame.origin.x > 0){
        [self.GPSInfoBaseView viewResetWithType:GPSInfoBaseViewReckRecordAfter DataSource:self.emergency_voices];
    }else{
        [self.GPSInfoBaseView viewResetWithType:GPSInfoBaseViewReckRecordBefore DataSource:self.emergency_voices];
    }
}
- (IBAction)callPolice:(id)sender {
    [self showPhonesActionSheet];
}
- (IBAction)callSbneedHelp:(id)sender {
    [self callPhonesActionSheet: self.helpInfo[@"emergency_info"][@"mobile"]];
}
- (IBAction)callYourContract:(id)sender {
    [self.view addSubview:self.GPSInfoBaseView];
    [UIView animateWithDuration:0.6 animations:^(void){
        self.GPSInfoBaseView.alpha =1.0f;
    }];
    switch ([sender tag]) {
        case 88:
            [self.GPSInfoBaseView viewResetWithType:GPSInfoBaseViewReckContractBefore DataSource:self.sbContract];
            break;
        case 98:
             [self.GPSInfoBaseView viewResetWithType:GPSInfoBaseViewReckContractAfter DataSource:self.sbContract];
            break;

    }
}
- (void)getSbContractinfo{
    @weakify(self)
    [[[HttpManagerCenter sharedHttpManager] getSbContractInfo:self.params[@"emergency_id"] resultClass:nil] subscribeNext:^(BaseModel *model){
        @strongify(self)
        if(model.code==200){
            self.sbContract = [NSArray arrayWithArray:model.data];
        }else{
            [self hiddenHUDWithString:@"获取信息失败" error:NO];
        }
    } error:^(NSError *error) {
        [self hiddenHUDWithString:@"获取信息失败" error:NO];
    } completed:^{
    }];
}
-(void)getThisHelpDetail{
    @weakify(self)
    [self showHUDWithString:nil];
    [[[HttpManagerCenter sharedHttpManager] getHelpInfo:self.params[@"emergency_id"] resultClass:nil] subscribeNext:^(BaseModel *model){
        @strongify(self)
        if(model.code==200){
            [self hiddenHUDWithString:@"刷新信息完成!" error:NO];
            self.helpInfo =model.data;
            self.emergency_voices = [NSMutableArray arrayWithArray:model.data[@"emergency_voices"]];
            [self initPropertiesLat:model.data[@"emergency_info"][@"lat"] AndLng:model.data[@"emergency_info"][@"lng"]];
            [self calculateRoute];
        }
    }];
}
#pragma mark - AMapNaviWalkManagerDelegate

- (void)walkManager:(AMapNaviWalkManager *)walkManager error:(NSError *)error
{
    NSLog(@"error:{%ld - %@}", (long)error.code, error.localizedDescription);
}

- (void)walkManagerOnCalculateRouteSuccess:(AMapNaviWalkManager *)walkManager
{
    NSLog(@"onCalculateRouteSuccess");
    [self.startGPS setEnabled:YES];
    [self.driveView setShowMode:AMapNaviWalkViewShowModeOverview];
    //算路成功后开始GPS导航
}

- (void)walkManager:(AMapNaviWalkManager *)walkManager onCalculateRouteFailure:(NSError *)error  //步行路径规划失败后的回调函数
{
    NSLog(@"onCalculateRouteFailure:{%ld - %@}", (long)error.code, error.localizedDescription);
}

- (void)walkManager:(AMapNaviWalkManager *)walkManager didStartNavi:(AMapNaviMode)naviMode //启动导航后回调函数
{
    NSLog(@"didStartNavi");
}

- (void)walkManagerNeedRecalculateRouteForYaw:(AMapNaviWalkManager *)walkManager // 出现偏航需要重新计算路径时的回调函数   
{
    NSLog(@"needRecalculateRouteForYaw");
}
- (void)walkManager:(AMapNaviWalkManager *)walkManager playNaviSoundString:(NSString *)soundString soundStringType:(AMapNaviSoundType)soundStringType
{
    NSLog(@"playNaviSoundString:{%ld:%@}", (long)soundStringType, soundString);
    
    [[SpeechSynthesizer sharedSpeechSynthesizer] speakString:soundString];
}

- (void)walkManagerDidEndEmulatorNavi:(AMapNaviWalkManager *)walkManager
{
    NSLog(@"didEndEmulatorNavi");
}

- (void)walkManagerOnArrivedDestination:(AMapNaviWalkManager *)walkManager
{
    NSLog(@"onArrivedDestination");
    [self stopWalkManager:nil];
}

#pragma mark - AMapNaviWalkDataRepresentable

- (void)walkManager:(AMapNaviWalkManager *)walkManager updateNaviInfo:(nullable AMapNaviInfo *)naviInfo{
    NSString *turnStr = [NSString stringWithFormat:@"%@后", [self normalizedRemainDistance:naviInfo.segmentRemainDistance]];
    [self.turnRemainInfoLabel setText:turnStr];
    //道路信息
    [self.roadInfoLabel setText:naviInfo.nextRoadName];
    //路径剩余信息
    NSString *routeStr = [NSString stringWithFormat:@"%@ %@", [self normalizedRemainDistance:naviInfo.routeRemainDistance], [self normalizedRemainTime:naviInfo.routeRemainTime]];
    [self.routeRemainInfoLabel setText:routeStr];
//    [self.routeDistanceInfoLabel setText:[self normalizedRemainDistance:naviInfo.routeRemainDistance]];
}
#pragma mark - AMapNaviWalkViewDelegate

- (void)walkViewCloseButtonClicked:(AMapNaviWalkView *)driveView
{
    //停止导航
    [self.driveManager stopNavi];
    [self.driveManager removeDataRepresentative:self.driveView];
    
    //停止语音
    [[SpeechSynthesizer sharedSpeechSynthesizer] stopSpeak];
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)walkViewTrunIndicatorViewTapped:(AMapNaviWalkView *)driveView
{
    NSLog(@"TrunIndicatorViewTapped");
}

- (void)walkView:(AMapNaviWalkView *)driveView didChangeShowMode:(AMapNaviWalkViewShowMode)showMode
{
    NSLog(@"didChangeShowMode:%ld", (long)showMode);
    switch ((int)showMode) {
        case AMapNaviWalkViewShowModeNormal:
            [self.roadBeforeLabel setHidden:YES];
            [self.routeRemainInfoLabel setHidden:YES];
            [self.backToNow setHidden:NO];
            break;
        case AMapNaviWalkViewShowModeCarPositionLocked:
            [self.roadBeforeLabel setHidden:NO];
            [self.routeRemainInfoLabel setHidden:NO];
            [self.backToNow setHidden:YES];
            break;
    }
    
    
}
#pragma mark - Utility

- (NSString *)normalizedRemainDistance:(NSInteger)remainDistance
{
    if (remainDistance < 0){
        return nil;
    }
    if (remainDistance >= 1000){
        CGFloat kiloMeter = remainDistance / 1000.0;
        
        if (remainDistance % 1000 >= 100){
            kiloMeter -= 0.05f;
            return [NSString stringWithFormat:@"%.1f公里", kiloMeter];
        }
        else{
            return [NSString stringWithFormat:@"%.0f公里", kiloMeter];
        }
    }
    else{
        return [NSString stringWithFormat:@"%ld米", (long)remainDistance];
    }
}

- (NSString *)normalizedRemainTime:(NSInteger)remainTime
{
    if (remainTime < 0){
        return nil;
    }
    if (remainTime < 60){
        return [NSString stringWithFormat:@"< 1分钟"];
    }
    else if (remainTime >= 60 && remainTime < 60*60){
        return [NSString stringWithFormat:@"%ld分钟", (long)remainTime/60];
    }
    else{
        NSInteger hours = remainTime / 60 / 60;
        NSInteger minute = remainTime / 60 % 60;
        if (minute == 0){
            return [NSString stringWithFormat:@"%ld小时", (long)hours];
        }
        else{
            return [NSString stringWithFormat:@"%ld小时%ld分钟", (long)hours, (long)minute];
        }
    }
}
-(void)clearThisViewController{
    self.driveManager = nil;
    self.driveView = nil;
    [self.driveManager removeDataRepresentative:self];
    [[SpeechSynthesizer sharedSpeechSynthesizer] stopSpeak];
    [self.driveManager removeDataRepresentative:self.driveView];
}

-(void)dealloc{
    [self clearThisViewController];
}
@end
